import * as React from 'react';
import {
  Form,
  Input,
  Modal,
  Select,
  message,
  Table,
  Col,
  Row,
  Button,
} from 'antd';
import request from '@/http';
import '@/pages/admin/studentInfo/addClass.less';
import qs from 'qs';
import { useState } from 'react';

const { Option } = Select;

interface AStudentObject {
  isModalVisible: boolean;
  id?: number;
  collegesName?: string;
  stuMajor?: string;
  grade?: string;
  className?: string;
  teacherName?: string;
  status?: number;
  stuTotal?: number;
  groupId?: any;
}

//学生信息管理  （新增）  （编辑）
const AStudent = (props: { editObject: AStudentObject; onClose: any }) => {
  const columns = [
    {
      title: '小组名称',
      dataIndex: 'teamName',
      key: 'teamName',
      width: 120,
    },
    {
      title: '院系',
      dataIndex: 'collegesName',
      key: 'collegesName',
      width: 100,
    },
    {
      title: '专业',
      dataIndex: 'majorName',
      key: 'majorName',
      width: 100,
    },
    {
      title: '年级',
      dataIndex: 'gradeName',
      key: 'gradeName',
      width: 75,
    },
    {
      title: '班级',
      dataIndex: 'className',
      key: 'className',
      width: 75,
    },
    {
      title: '班主任 ',
      dataIndex: 'teacherName',
      key: 'teacherName',
      width: 100,
    },
    {
      title: '学员姓名',
      dataIndex: 'studentName',
      key: 'studentName',
      width: 100,
    },
    {
      title: '学号',
      dataIndex: 'userNo',
      key: 'userNo',
      width: 100,
      textAlign: 'center',
    },
    {
      title: '身份证号码',
      dataIndex: 'idNo',
      key: 'idNo',
      width: 110,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      width: 75,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 100,
    },
    {
      title: '手机号',
      dataIndex: 'mobileNo',
      key: 'mobileNo',
      width: 100,
    },
    {
      title: '项目角色',
      dataIndex: 'position',
      key: 'position',
      width: 100,
    },
  ];
  const [dataSourceR, setDataSourceR] = React.useState<any[]>([]);

  const [pagination, setPagination] = React.useState({
    current: 1,
    total: 10,
    pageSize: 5,
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '50', '200', '500'],
    showQuickJumper: true,
  });

  const [loadingStateR, setLoadingStateR] = React.useState({ loading: false });

  const showSource = async (
    groupNameList: any,
    pageValue: any,
    pageSize: any,
  ) => {
    setLoadingStateR({ loading: true });

    if (localStorage.getItem('team_name')) {
      const ds = {
        teamName: localStorage.getItem('team_name'),
        currentPage: pageValue ? pageValue : 1,
        size: pageSize ? pageSize : 10,
      };
      const result: any = await request.post(
        '/api/admin/group/TermSelTeamStudent',
        qs.stringify(ds),
      );
      if (result.code == '200') {
        const data = result.data.data.map((user: any) => ({
          key: user.id,
          id: user.id,
          teamName: user.teamName,
          collegesName: user.collegesName,
          majorName: user.majorName,
          gradeName: user.gradeName,
          className: user.className,
          teacherName: user.teacherName,
          studentName: user.studentName,
          userNo: user.userNo,
          idNo: user.idNo,
          sex: user.sex,
          email: user.email,
          mobileNo: user.mobileNo,
          position: user.position,
          teamIsLeader: user.teamIsLeader,
        }));
        setDataSourceR(data);
        setLoadingStateR({ loading: false });
      }
    } else {
      //message.error('请选择小组名称');
    }
  };

  const { editObject, onClose } = props;
  const [isModalVisible, setIsModalVisible] = React.useState(false);
  const [formObject] = Form.useForm();

  const selectCourse = async () => {
    const data = await formObject.getFieldsValue();
    const ds = {
      currentPage: 1,
      size: 5,
      className: data.className,
      collegesName: data.collegesName,
      gradeName: data.gradeName,
      majorName: data.majorName,
      studentName: data.studentName,
      userNo: data.stuTotal,
    };
    const result: any = await request.post(
      '/api/admin/group/TermSelStudentNotInTeam',
      qs.stringify(ds),
    );
    if (result.code == '200') {
      if (result.data.total != 0) {
        const data = result.data.data.map((user: any) => ({
          key: user.id,
          id: user.id,
          teamName: user.teamName,
          collegesName: user.collegesName,
          majorName: user.majorName,
          gradeName: user.gradeName,
          className: user.className,
          teacherName: user.teacherName,
          studentName: user.studentName,
          userNo: user.userNo,
          idNo: user.idNo,
          sex: user.sex,
          email: user.email,
          mobileNo: user.mobileNo,
          position: user.position,
          teamIsLeader: user.teamIsLeader,
        }));
        setDataSourceR(data);
      } else {
        message.success('暂无未分组学生');
        //setDataSourceR(data);
      }
      setLoadingStateR({ loading: false });
    }
  };

  const resetForm = () => {
    formObject.resetFields();
    showSource(formObject.getFieldsValue(), 1, pagination.pageSize);
  };

  const [state, setState] = React.useState({
    selectedRowId: [],
    loading: false,
  });

  const { loading, selectedRowId } = state;

  function onSelectChange(selectedRowId: any) {
    setState({ loading: false, selectedRowId });
    localStorage.setItem('selectedRowId', selectedRowId);
  }

  const rowSelection = {
    selectedRowId,
    onChange: onSelectChange,
  };

  const modelOnOk = async () => {
    let a = localStorage.getItem('selectedRowId');
    console.log(a);
    let teamName = localStorage.getItem('team_name');
    const ds = {
      studentIds: a,
      teamName: teamName,
    };
    const result: any = await request.post(
      '/api/admin/group/InsertStudentToTeam',
      qs.stringify(ds),
    );
    if (result.code == 200) {
      message.success('新增成功');
      setIsModalVisible(false);
    } else {
      message.success('该学生已新增过');
    }
  };

  const modelOnCancel = () => {
    setIsModalVisible(false);
  };

  React.useEffect(() => {
    setIsModalVisible(editObject.isModalVisible);
    selectDataSource();
    showSource(formObject.getFieldsValue(), 1, pagination.pageSize);
    if (editObject.id !== null) {
      formObject.setFieldsValue({
        collegesName: editObject.collegesName,
        stuMajor: editObject.stuMajor,
        grade: editObject.grade,
        className: editObject.className,
        teacherName: editObject.teacherName,
        status: editObject.status,
        stuTotal: editObject.stuTotal,
      });
    }
  }, [editObject]);

  const [groupName, setGroupName] = useState([]);

  const [majorName, setMajorName] = useState([]);

  const [gradeName, setGradeName] = useState([]);

  const [className, setClassName] = useState([]);

  const selectDataSource = async () => {
    const groupData: any = await request.post(
      '/api/common_module/a_t_s/getTeam',
    );
    setGroupName(groupData.data);
    const majorData: any = await request.post(
      '/api/common_module/a_t_s/getMajor',
    );
    setMajorName(majorData.data);
    const gradeName: any = await request.post(
      '/api/common_module/a_t_s/getGrade',
    );
    setGradeName(gradeName.data);
    const className: any = await request.post(
      '/api/common_module/a_t_s/getClassInfo',
    );
    setClassName(className.data);
  };

  const formItemLayout = {
    labelCol: {
      span: 7,
    },
    wrapperCol: {
      span: 24,
    },
  };

  //有id为真 编辑班级信息
  const flag = editObject.id !== null && editObject.id !== undefined;

  return (
    <>
      <Modal
        width={1200}
        className="modal"
        title={flag ? '编辑班级信息' : '新增成员'}
        visible={isModalVisible}
        onCancel={modelOnCancel}
        onOk={modelOnOk}
        maskClosable={false}
        destroyOnClose
        okText="确认"
        cancelText="取消"
      >
        <Form
          className="form"
          name="editForm"
          form={formObject}
          preserve={false}
          {...formItemLayout}
        >
          <Row gutter={24} style={{ width: '100%' }}>
            <Col span={8}>
              <Form.Item label="小组名称" name="teamName">
                <Select style={{ width: '100%' }} placeholder="请选择">
                  {(groupName || []).map((groupName: any) => {
                    return (
                      <option key={groupName.teamId} value={groupName.teamName}>
                        {groupName.teamName}
                      </option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="专业" name="majorName">
                <Select style={{ width: '100%' }} placeholder="请选择">
                  {(majorName || []).map((majorName: any) => {
                    return (
                      <option
                        key={majorName.majorId}
                        value={majorName.majorName}
                      >
                        {majorName.majorName}
                      </option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="年级" name="gradeName">
                <Select style={{ width: '100%' }} placeholder="请选择">
                  {(gradeName || []).map((gradeName: any) => {
                    return (
                      <option
                        key={gradeName.gradeId}
                        value={gradeName.gradeName}
                      >
                        {gradeName.gradeName}
                      </option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24} style={{ width: '100%' }}>
            <Col span={8}>
              <Form.Item label="班级" name="className">
                <Select style={{ width: '100%' }} placeholder="请选择">
                  {(className || []).map((className: any) => {
                    return (
                      <option
                        key={className.classId}
                        value={className.className}
                      >
                        {className.className}
                      </option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="学员姓名" name="stuTotal">
                <Input className=" addsInput" placeholder="请输入..." />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="学号" name="teacherName">
                <Input className="addsInput" placeholder="请输入..." />
              </Form.Item>
            </Col>
          </Row>
          <Row style={{ marginLeft: '85%' }}>
            <Button type="primary" onClick={selectCourse}>
              查询
            </Button>
            <Button style={{ marginLeft: 20 }} onClick={resetForm}>
              重置
            </Button>
          </Row>
        </Form>
        <Table
          scroll={{ x: 'max-content' }}
          className="ptTable"
          rowSelection={rowSelection}
          columns={columns}
          //onChange={pageOnChange}
          dataSource={dataSourceR}
        />
      </Modal>
    </>
  );
};

export { AStudent, AStudentObject };
